#!/bin/bash
#
# startup.sh -- lab specific startup script,
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

TOP_DIR=$(cd $(dirname $0) && pwd)/

[ ! -d /proc ] && mount -t proc none /proc

# nfsd.ko must be inserted to enable nfs kernel server
grep -qi intel /proc/cpuinfo
if [ $? -eq 0 ]; then
  kvm_dri=kvm-intel
else
  kvm_dri=kvm-amd
fi

# FIXME: with linux kernel v5.3, v5.4, v5.6, nfsd has bug while be plugged in
# container side, but ok in host side, move it back to host side:
# https://gitee.com/tinylab/linux-lab/issues/I1GGG1
#
# This may break nfsboot in Windows 10 and Mac OSX, there is no suitable method
# to insert nfsd in 'host' side.

os=`uname`
if [ "$os" = "Linux" ]; then
  uname -r | grep ^[5-9]
  [ $? -ne 0 ] && NFS=nfsd
else
  # Insert nfsd in container side for Windows and Mac OS X currently for there is
  # no method to insert nfs module.
  #
  # If they use the same kernel, it should crash too ...
  NFS=nfsd
fi

modules="loop minix $NFS 9pnet_virtio kvm $kvm_dri"

for m in $modules
do
  modprobe -d /m -n $m >/dev/null 2>&1
  [ $? -ne 0 ] && continue

  lsmod | grep -q $m
  [ $? -ne 0 ] && modprobe -d /m $m >/dev/null 2>&1

  # tell user enable cpu virtualization in bios if not disabled
  if [ $? -ne 0 ]; then
    if [ "$m" = "kvm-intel" -o "$m" = "kvm-amd" ]; then
      echo "LOG: Please turn on cpu virtualization in bios if want use kvm speedup"
    fi
  fi
done

# For qemu-mips64el
[ ! -f /proc/sys/fs/binfmt_misc/regisiter ] && mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
if [ ! -f /proc/sys/fs/binfmt_misc/mips64el -a -f /proc/sys/fs/binfmt_misc/register ]; then
  sh -c "echo ':mips64el:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x08\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-mips64el:' > /proc/sys/fs/binfmt_misc/register"
fi

# Configure for core-dump
# echo "/tmp/cores/core.%e.%p" > /proc/sys/kernel/core_pattern
echo core > /proc/sys/kernel/core_pattern

# Enable network bridge support

$TOP_DIR/enable_net_bridge.sh

## Start Net servers
$TOP_DIR/restart-net-servers.sh

## Install aarch64-linux-gnu-gcc alternatives
[ -f /usr/bin/aarch64-linux-gnu-gcc-4.8 ] && \
  update-alternatives --install /usr/bin/aarch64-linux-gnu-gcc aarch64-linux-gnu-gcc /usr/bin/aarch64-linux-gnu-gcc-4.8 45
[ -f /usr/local/bin/aarch64-linux-gnu-gcc-4.9.3 ] && \
  ln -sf /usr/local/bin/aarch64-linux-gnu-gcc-4.9.3 /usr/bin/aarch64-linux-gnu-gcc-4.9.3 && \
  update-alternatives --install /usr/bin/aarch64-linux-gnu-gcc aarch64-linux-gnu-gcc /usr/bin/aarch64-linux-gnu-gcc-4.9.3 46

# FIXME: Disable git detachedHead advice, bsp submodule use FETCH_HEAD currently.
git config --global advice.detachedHead false
